<!-- 用户管理 -->
<template>
  <div>
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :lg="5" :xs="24" class="mb-[12px] Usercontainer">
        <el-card shadow="never" class="elTree">
          <div class="client">
            <div class="list">
              <el-icon style="margin-right: 5px" size="20">
                <UserFilled />
              </el-icon>
              客户列表
            </div>
            <!-- <el-button type="primary" size="small" v-hasPerm="['Device:add']">添加</el-button> -->
          </div>
          <dept-tree v-model="queryParams.customerId" @node-click="handleQuery" />
        </el-card>
      </el-col>
      <!-- 用户列表 -->
      <el-col :lg="19" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input v-model="queryParams.keyword" placeholder="用户名/昵称/手机号" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.enableFlag" placeholder="全部" clearable class="!w-[100px]">
                <el-option label="启用" value="ENABLE" />
                <el-option label="禁用" value="DISABLE" />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker v-model="dateTimeRange" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <!-- <i-ep-search /> -->
                搜索
              </el-button>
              <el-button @click="handleResetQuery">
                <!-- <i-ep-refresh /> -->
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <!-- v-hasPerm="['sys:user:add']" -->
                <el-button type="success" @click="handleOpenDialog()" v-hasPerm="['Device:add']">
                  <i-ep-plus />
                  新增
                </el-button>
                <!-- v-hasPerm="['sys:user:delete']" -->
                <!-- <el-button type="danger" :disabled="removeIds.length === 0" @click="handleDelete()">
                  <i-ep-delete />
                  删除
                </el-button> -->
              </div>
              <div>
                <!-- <template #icon><i-ep-upload /></template> -->

                <!-- <el-button class="ml-3" @click="handleOpenImportDialog">
                  导入
                </el-button> -->
                <!-- <template #icon><i-ep-download /></template> -->

                <!-- <el-button class="ml-3" @click="handleExport">
                  导出
                </el-button> -->
              </div>
            </div>
          </template>

          <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column key="id" label="编号" align="center" prop="id" width="200" />
            <el-table-column key="username" label="用户名" align="center" prop="username" />
            <el-table-column label="用户昵称" width="120" align="center" prop="name" />

            <el-table-column label="性别" width="100" align="center" prop="genderLabel" />

            <el-table-column label="部门" width="120" align="center" prop="deptName" />
            <el-table-column label="手机号码" align="center" prop="phone" width="120" />

            <!-- <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
                  {{ scope.row.status == 1 ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column> -->
            <el-table-column label="创建时间" align="center" prop="createTime" width="280" />
            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <!-- v-hasPerm="['sys:user:password:reset']" -->
                <el-button type="primary" size="small" link @click="hancleResetPassword(scope.row)"
                  v-hasPerm="['Device:add']">
                  <!-- <i-ep-refresh-left /> -->
                  重置密码
                </el-button>
                <!-- v-hasPerm="['sys:user:edit']" -->
                <el-button type="primary" link size="small" @click="handleOpenDialog(scope.row.id)"
                  v-hasPerm="['Device:add']">
                  <!-- <i-ep-edit /> -->
                  编辑
                </el-button>
                <!-- v-hasPerm="['sys:user:delete']"  -->
                <el-button type="danger" link size="small" @click="handleDelete(scope.row.id)"
                  v-hasPerm="['Device:add']">
                  <!-- <i-ep-delete /> -->
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-if="queryParams.pages.total > 0" v-model:total="queryParams.pages.total"
            v-model:page="queryParams.pages.current" v-model:limit="queryParams.pages.size" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单弹窗 -->
    <el-drawer v-model="dialog.visible" :title="dialog.title" append-to-body @close="handleCloseDialog">
      <!-- 用户新增/编辑表单 -->
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" :readonly="!!formData.id" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="dialog.title !== '修改用户'">
          <el-input v-model="formData.password" placeholder="请输入密码" maxlength="11" />
        </el-form-item>
        <el-form-item label="所属客户" prop="customerId">
          <el-tree-select v-model="formData.customerId" placeholder="请选择所属客户"
            :props="{ children: 'children', label: 'customerName', value: 'id' }" :data="deptOptions" filterable
            check-strictly :render-after-expand="false" />
        </el-form-item>

        <!-- <dictionary v-model="formData.gender" code="gender" /> -->
        <!-- <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择性别" clearable>
            <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="角色" prop="roleIdList">
          <el-select v-model="formData.roleIdList" multiple placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
              :value="item.value ? item.value : ''" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <!-- <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item> -->

        <el-form-item label="状态" prop="enableFlag">
          <el-radio-group v-model="formData.enableFlag">
            <el-radio value="ENABLE">正常</el-radio>
            <el-radio value="DISABLE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 用户导入弹窗 -->
    <!-- <user-import v-model:visible="importDialogVisible" @import-success="handleOpenImportDialogSuccess" /> -->
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import UserAPI, { UserForm, UserPageQuery, UserPageVO } from "@/api/user";
// import DeptAPI from "@/api/dept";
import CustomerAPI from "@/api/customer";
import RoleAPI from "@/api/role";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);
const loading = ref(false);
const removeIds = ref([]);
const pageData = ref<UserPageVO[]>();
/** 部门下拉选项 */
const deptOptions = ref<OptionType[]>();
/** 角色下拉选项 */
const roleOptions = ref<OptionType[]>();
/** 用户查询参数  */
const queryParams = reactive<UserPageQuery>({
  "pages": {
    "current": 1,
    "size": 10,
    "total": 0,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  enableFlag: undefined,
  customerId: undefined,
  keyword: ""
});

const dateTimeRange = ref("");
// watch(dateTimeRange, (newVal) => {
//   if (newVal) {
//     queryParams.startTime = newVal[0];
//     queryParams.endTime = newVal[1];
//   } else {
//     queryParams.startTime = undefined;
//     queryParams.endTime = undefined;
//   }
// });

/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

/** 导入弹窗显示状态 */
const importDialogVisible = ref(false);

// 用户表单数据
const formData = reactive<UserForm>({});

/** 用户表单校验规则  */
const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  customerId: [{ required: true, message: "所属客户不能为空", trigger: "blur" }],
  roleIdList: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }],
  name: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  console.log(dateTimeRange.value, 'dateTimeRange.value');

  if (dateTimeRange.value) {
    queryParams.pages.startTime = dateTimeRange.value[0]
    queryParams.pages.endTime = dateTimeRange.value[1]
  } else {
    queryParams.pages.startTime = ''
    queryParams.pages.endTime = ''
  }
  UserAPI.getPage(queryParams)
    .then((data) => {
      console.log("handleQuery", data);
      pageData.value = data.records;
      queryParams.pages.total = data.total;
      queryParams.pages.current = data.current;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.pages.current = 1;
  queryParams.pages.enableFlag = undefined;
  queryParams.pages.username = undefined;
  queryParams.keyword = undefined;
  dateTimeRange.value = ''
  dateTimeRange
  queryParams.pages.customerId = undefined;
  queryParams.pages.phone = undefined;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 重置密码 */
function hancleResetPassword(row: { [key: string]: any }) {

  ElMessageBox.confirm(
    // "请输入用户「" + row.username + "」的新密码",
    "是否重置密码",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }
  ).then(
    () => {
      // if (!value || value.length < 6) {
      //   // 检查密码是否为空或少于6位
      //   ElMessage.warning("密码至少需要6位字符，请重新输入");
      //   return false;
      // }
      UserAPI.resetPassword(row.id).then(() => {
        ElMessage.success("密码重置成功");
      });
    },
    () => {
      ElMessage.info("已取消重置密码");
    }
  );
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: string) {
  dialog.visible = true;
  // 加载角色下拉数据源
  roleOptions.value = await RoleAPI.getOptions();
  // 加载部门下拉数据源
  deptOptions.value = []
  deptOptions.value.push(await CustomerAPI.getCustomerTree())

  if (id) {
    dialog.title = "修改用户";
    UserAPI.getFormData(id).then((data) => {
      const { createTime, ...rest } = data;
      Object.assign(formData, rest);
    });
  } else {
    dialog.title = "新增用户";
  }
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  // formData = reactive<UserForm>({})
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        UserAPI.update(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.add(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}
/** 打开导入弹窗 */
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

/** 导入用户成功 */
function handleOpenImportDialogSuccess() {
  handleQuery();
}

/** 导出用户 */
function handleExport() {
  UserAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

onMounted(() => {
  // handleQuery();
});
</script>
<style lang="scss" scoped>
.Usercontainer {
  :deep(.el-card__body) {
    padding: var(--el-card-padding) !important;
    padding-top: 0 !important;
  }
}
</style>
